package com.xzz.directprint.util;

/**
 * @Author: zhanglm
 * @CreateDate: 2024-11-17 14:07
 * @FullNameClass: com.xzz.directprint.util.PrintPDF
 * @Description:
 */
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.IOException;

public class PrintPDF {
    public static void main(String[] args) throws IOException, PrinterException {
        // 要打印的PDF文件路径
        String pdfFilePath = "D:/ab.pdf";

        // 加载PDF文档
        PDDocument document = PDDocument.load(new File(pdfFilePath));

        // 创建一个打印任务
        PrinterJob job = PrinterJob.getPrinterJob();
        job.setPageable(new PDFPageable(document));

        // 查找并设置打印机
        PrintService defaultPrintService = PrintServiceLookup.lookupDefaultPrintService();
        if (defaultPrintService != null) {
            job.setPrintService(defaultPrintService);
        }

        // 直接打印
        job.print();

        // 关闭PDF文档
        document.close();
    }
}
